package com.snapp.annot;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;

import com.impetus.annovention.Discoverer;
import com.impetus.annovention.Filter;
import com.impetus.annovention.FilterImpl;

public class SnappClasspathDiscoverer extends Discoverer {
	static Logger log = Logger.getLogger(SnappClasspathDiscoverer.class);
	
	/** The filter. */
    private Filter filter;
    private ServletContext context;

    /**
     * Instantiates a new classpath reader.
     */
    public SnappClasspathDiscoverer(ServletContext context) {
            filter = new FilterImpl();
            this.context = context;
    }

    /**
     * Uses java.class.path system-property to fetch URLs
     * 
     * @return the URL[]
     */
    @SuppressWarnings("deprecation")
    @Override
    public final URL[] findResources() {
            List<URL> list = new ArrayList<URL>();
            
            String classpath = System.getProperty("java.class.path");
            //String classpath = "C:/Users/Kile/jboss-6.0.0.M2/jboss-6.0.0.20100216-M2/server/all/farm/snapp.ear/snapp_util.jar";
            
            StringTokenizer tokenizer = new StringTokenizer(classpath,
    				File.pathSeparator);
    		
    		while (tokenizer.hasMoreTokens()) {
                    String path = tokenizer.nextToken();
                    
                    log.info("PATH: " + path);
                    
                    try {
                            path = java.net.URLDecoder.decode(path, "UTF-8");
                    } catch (UnsupportedEncodingException e1) {
                    }
                    File fp = new File(path);
                    if (!fp.exists())
                            throw new RuntimeException(
                                            "File in java.class.path does not exist: " + fp);
                    try {
                            list.add(fp.toURL());
                    } catch (MalformedURLException e) {
                            throw new RuntimeException(e);
                    }
            }
            return list.toArray(new URL[list.size()]);
    }

    /* @see com.impetus.annovention.Discoverer#getFilter() */
    public final Filter getFilter() {
            return filter;
    }

    /**
     * @param filter
     */
    public final void setFilter(Filter filter) {
            this.filter = filter;
    }
}
